package com.example.socialapp.ui.profile

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.BarChart
import androidx.compose.material.icons.filled.ChatBubbleOutline
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Hub
import androidx.compose.material.icons.filled.Interests
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PersonAdd
import androidx.compose.material.icons.filled.PersonRemove
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material.icons.filled.Work
import androidx.compose.material.icons.outlined.InsertComment
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.absoluteValue
import kotlin.random.Random

/**
 * 用户资料界面
 * 
 * @param userId 用户ID
 * @param onNavigateBack 返回上一界面回调
 * @param onNavigateToChat 导航到聊天界面回调
 * @param onNavigateToPostDetail 导航到动态详情界面回调
 * @param onNavigateToUserStats 导航到用户统计界面回调
 * @param onNavigateToSocialGraph 导航到社交关系图界面回调
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UserProfileScreen(
    userId: String = "user-1",  // Default user ID for preview
    onNavigateBack: () -> Unit,
    onNavigateToChat: (String) -> Unit = {},
    onNavigateToPostDetail: (String) -> Unit = {},
    onNavigateToUserStats: (String) -> Unit = {},
    onNavigateToSocialGraph: (String) -> Unit = {}
) {
    // 在实际应用中应从ViewModel获取用户信息和动态列表
    val user = remember { generateSampleUser(userId) }
    val posts = remember { generateSamplePosts(userId, 10) }
    
    var selectedTab by remember { mutableIntStateOf(0) }
    val tabs = listOf("动态", "相册", "喜欢")
    
    var isFollowing by remember { mutableStateOf(false) }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("用户资料") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = { /* 分享用户资料 */ }) {
                        Icon(
                            imageVector = Icons.Default.Share,
                            contentDescription = "分享"
                        )
                    }
                    IconButton(onClick = { /* 更多选项 */ }) {
                        Icon(
                            imageVector = Icons.Default.MoreVert,
                            contentDescription = "更多选项"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        }
    ) { innerPadding ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
        ) {
            // 用户信息卡片
            item {
                UserProfileCard(
                    user = user,
                    isFollowing = isFollowing,
                    onFollowClick = { isFollowing = !isFollowing },
                    onChatClick = { onNavigateToChat(userId) }
                )
                
                // 选项卡
                TabRow(
                    selectedTabIndex = selectedTab,
                    containerColor = MaterialTheme.colorScheme.surface
                ) {
                    tabs.forEachIndexed { index, title ->
                        Tab(
                            selected = selectedTab == index,
                            onClick = { selectedTab = index },
                            text = { Text(text = title) }
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
            }
            
            // 内容区域
            when (selectedTab) {
                0 -> { // 动态
                    if (posts.isEmpty()) {
                        item {
                            EmptyContent(text = "暂无动态")
                        }
                    } else {
                        items(posts) { post ->
                            PostItem(
                                post = post,
                                onPostClick = { onNavigateToPostDetail(post.id) }
                            )
                            Divider()
                        }
                    }
                }
                1 -> { // 相册
                    item {
                        EmptyContent(text = "暂无相册")
                    }
                }
                2 -> { // 喜欢
                    item {
                        EmptyContent(text = "暂无喜欢的内容")
                    }
                }
            }
            
            item {
                UserStats()
            }
            
            item {
                Spacer(modifier = Modifier.height(16.dp))
                
                // 分析与社交关系图
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 活跃度统计按钮
                    Button(
                        onClick = { onNavigateToUserStats(userId) },
                        modifier = Modifier.weight(1f),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.secondaryContainer,
                            contentColor = MaterialTheme.colorScheme.onSecondaryContainer
                        )
                    ) {
                        Icon(
                            imageVector = Icons.Default.BarChart,
                            contentDescription = null,
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("活跃度统计")
                    }
                    
                    // 社交关系图按钮
                    Button(
                        onClick = { onNavigateToSocialGraph(userId) },
                        modifier = Modifier.weight(1f),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.tertiaryContainer,
                            contentColor = MaterialTheme.colorScheme.onTertiaryContainer
                        )
                    ) {
                        Icon(
                            imageVector = Icons.Default.Hub,
                            contentDescription = null,
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("社交关系图")
                    }
                }
            }
        }
    }
}

/**
 * 用户资料卡片组件
 */
@Composable
private fun UserProfileCard(
    user: UserProfile,
    isFollowing: Boolean,
    onFollowClick: () -> Unit,
    onChatClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surface
        )
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            // 头像和用户名
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 头像
                Box(
                    modifier = Modifier
                        .size(80.dp)
                        .clip(CircleShape)
                        .background(getColorForName(user.nickname)),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = user.nickname.first().toString(),
                        style = MaterialTheme.typography.headlineMedium,
                        color = Color.White
                    )
                }
                
                Spacer(modifier = Modifier.width(16.dp))
                
                // 用户信息
                Column {
                    Text(
                        text = user.nickname,
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold
                    )
                    
                    Spacer(modifier = Modifier.height(4.dp))
                    
                    Text(
                        text = "ID: ${user.id}",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
            }
            
            // 个人简介
            if (user.bio.isNotEmpty()) {
                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    text = user.bio,
                    style = MaterialTheme.typography.bodyMedium
                )
            }
            
            // 交互统计
            Spacer(modifier = Modifier.height(16.dp))
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                StatItem(
                    label = "动态",
                    value = user.posts.toString()
                )
                StatItem(
                    label = "关注",
                    value = user.following.toString()
                )
                StatItem(
                    label = "粉丝",
                    value = user.followers.toString()
                )
            }
            
            // 操作按钮
            Spacer(modifier = Modifier.height(16.dp))
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                Button(
                    onClick = onFollowClick,
                    modifier = Modifier.weight(1f),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary
                    )
                ) {
                    Icon(
                        imageVector = if (isFollowing) Icons.Default.PersonRemove else Icons.Default.PersonAdd,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(text = if (isFollowing) "取消关注" else "关注")
                }
                
                Spacer(modifier = Modifier.width(8.dp))
                
                Button(
                    onClick = onChatClick,
                    modifier = Modifier.weight(1f),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.secondary
                    )
                ) {
                    Icon(
                        imageVector = Icons.Default.BarChart,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(text = "活跃度")
                }
            }
        }
    }
}

/**
 * 统计项组件
 */
@Composable
private fun StatItem(
    label: String,
    value: String
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = value,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.Bold
        )
        Text(
            text = label,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.outline
        )
    }
}

/**
 * 动态项组件
 */
@Composable
private fun PostItem(
    post: Post,
    onPostClick: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onPostClick() }
            .padding(16.dp)
    ) {
        // 内容
        Text(
            text = post.content,
            style = MaterialTheme.typography.bodyLarge,
            maxLines = 3,
            overflow = TextOverflow.Ellipsis
        )
        
        // 如果有图片
        if (post.hasImage) {
            Spacer(modifier = Modifier.height(8.dp))
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(120.dp)
                    .clip(RoundedCornerShape(8.dp))
                    .background(MaterialTheme.colorScheme.secondaryContainer),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "图片内容",
                    style = MaterialTheme.typography.bodyLarge,
                    color = MaterialTheme.colorScheme.onSecondaryContainer
                )
            }
        }
        
        // 时间和交互
        Spacer(modifier = Modifier.height(8.dp))
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 时间
            Text(
                text = post.formattedTime,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.outline
            )
            
            // 交互图标
            Row(
                horizontalArrangement = Arrangement.spacedBy(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 点赞
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { /* 点赞逻辑 */ }
                ) {
                    Icon(
                        imageVector = if (post.isLiked) 
                            Icons.Default.Favorite 
                        else 
                            Icons.Default.FavoriteBorder,
                        contentDescription = "点赞",
                        modifier = Modifier.size(16.dp),
                        tint = if (post.isLiked) Color.Red else MaterialTheme.colorScheme.outline
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = post.likes.toString(),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
                
                // 评论
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { onPostClick() }
                ) {
                    Icon(
                        imageVector = Icons.Outlined.InsertComment,
                        contentDescription = "评论",
                        modifier = Modifier.size(16.dp),
                        tint = MaterialTheme.colorScheme.outline
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = post.comments.toString(),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
            }
        }
    }
}

/**
 * 空内容显示组件
 */
@Composable
private fun EmptyContent(text: String) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(200.dp),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = text,
            style = MaterialTheme.typography.bodyLarge,
            color = MaterialTheme.colorScheme.outline,
            textAlign = TextAlign.Center
        )
    }
}

/**
 * 根据名称生成颜色
 */
private fun getColorForName(name: String): Color {
    val colors = listOf(
        Color(0xFF6200EA), // 深紫色
        Color(0xFF2962FF), // 深蓝色
        Color(0xFF00BFA5), // 青色
        Color(0xFFFFAB00), // 琥珀色
        Color(0xFFD50000)  // 红色
    )
    
    return colors[name.hashCode().mod(colors.size).absoluteValue]
}

/**
 * 用户资料数据类
 */
data class UserProfile(
    val id: String,
    val nickname: String,
    val bio: String,
    val posts: Int,
    val following: Int,
    val followers: Int
)

/**
 * 动态数据类
 */
data class Post(
    val id: String,
    val authorId: String,
    val content: String,
    val timestamp: Long,
    val likes: Int,
    val comments: Int,
    val hasImage: Boolean,
    val isLiked: Boolean
) {
    val formattedTime: String
        get() {
            val now = System.currentTimeMillis()
            val diff = now - timestamp
            
            return when {
                diff < 60 * 1000 -> "刚刚"
                diff < 60 * 60 * 1000 -> "${diff / (60 * 1000)}分钟前"
                diff < 24 * 60 * 60 * 1000 -> "${diff / (60 * 60 * 1000)}小时前"
                else -> {
                    val sdf = SimpleDateFormat("MM-dd", Locale.getDefault())
                    sdf.format(Date(timestamp))
                }
            }
        }
}

/**
 * 生成示例用户资料
 */
private fun generateSampleUser(userId: String): UserProfile {
    val userMap = mapOf(
        "10086" to UserProfile(
            id = "10086",
            nickname = "张三",
            bio = "热爱旅行和摄影，记录生活中的美好瞬间。云南大理是我的下一站！",
            posts = 56,
            following = 128,
            followers = 237
        ),
        "10087" to UserProfile(
            id = "10087",
            nickname = "李四",
            bio = "美食博主，分享各地美食和攻略。",
            posts = 89,
            following = 235,
            followers = 543
        ),
        "10088" to UserProfile(
            id = "10088",
            nickname = "王五",
            bio = "科技爱好者，关注最新的科技动态。",
            posts = 34,
            following = 78,
            followers = 132
        ),
        "10089" to UserProfile(
            id = "10089",
            nickname = "赵六",
            bio = "音乐创作者，热爱分享原创音乐作品。",
            posts = 67,
            following = 143,
            followers = 289
        )
    )
    
    return userMap[userId] ?: UserProfile(
        id = userId,
        nickname = "用户$userId",
        bio = "这个人很懒，什么都没有留下。",
        posts = Random.nextInt(10, 100),
        following = Random.nextInt(50, 300),
        followers = Random.nextInt(50, 500)
    )
}

/**
 * 生成示例动态列表
 */
private fun generateSamplePosts(userId: String, count: Int): List<Post> {
    val random = Random
    val currentTime = System.currentTimeMillis()
    val dayInMillis = 24 * 60 * 60 * 1000L
    
    val contents = listOf(
        "今天天气真好，出门走走感受一下阳光。",
        "新买的相机终于到货了，迫不及待地想要出去拍照！",
        "刚刚看完一部很感人的电影，推荐给大家：《肖申克的救赎》",
        "分享一个我最近学到的编程技巧，希望对大家有帮助。",
        "今天做了一道新菜，味道不错，有兴趣的朋友可以找我要菜谱。",
        "周末去了趟山里，空气清新，风景优美，真是放松身心的好地方。"
    )
    
    return List(count) { index ->
        Post(
            id = "$userId-post-$index",
            authorId = userId,
            content = contents[random.nextInt(contents.size)],
            timestamp = currentTime - random.nextLong(1, 30) * dayInMillis / random.nextInt(1, 30),
            likes = random.nextInt(5, 100),
            comments = random.nextInt(0, 30),
            hasImage = random.nextBoolean(),
            isLiked = random.nextBoolean()
        )
    }
}

/**
 * 用户统计信息组件
 */
@Composable
private fun UserStats() {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = "用户活跃度统计",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.primary
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 简单的统计信息展示
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    Text(
                        text = "86%",
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = "活跃度",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
                
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    Text(
                        text = "28天",
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = "连续活跃",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
                
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    Text(
                        text = "156",
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = "互动数",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
            }
        }
    }
} 